package com.zbkj.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.constants.OrderConstants;
import com.zbkj.common.constants.RedisConstants;
import com.zbkj.common.dto.OrderLocationDto;
import com.zbkj.common.dto.TuHuLocationDto;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.DeliveryPersonnel;
import com.zbkj.common.model.order.Order;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.order.RefundOrder;
import com.zbkj.common.model.product.ProductAttrValue;
import com.zbkj.common.model.saleroom.SaleRoom;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.*;
import com.zbkj.common.response.DeliveryPersonnelLoginResponse;
import com.zbkj.common.response.OrderFrontDataResponse;
import com.zbkj.common.response.OrderInfoFrontDataResponse;
import com.zbkj.common.token.FrontTokenComponent;
import com.zbkj.common.utils.*;
import com.zbkj.common.vo.MyRecord;
import com.zbkj.service.dao.DeliveryPersonnelDao;
import com.zbkj.service.dao.OrderDetailDao;
import com.zbkj.service.dao.ProductAttrValueDao;
import com.zbkj.service.dao.saleroom.SaleRoomDao;
import com.zbkj.service.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author keNan
 * @description DeliveryPersonnelServiceImpl 接口实现
 * @date 2025-03-12
 */
@Slf4j
@Service
public class DeliveryPersonnelServiceImpl extends ServiceImpl<DeliveryPersonnelDao, DeliveryPersonnel> implements DeliveryPersonnelService {

    @Resource
    private DeliveryPersonnelDao deliveryPersonnelDao;
    @Autowired
    private SaleRoomDao saleRoomDao;
    @Autowired
    private FrontTokenComponent tokenComponent;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductAttrValueDao productAttrValueDao;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RefundOrderService refundOrderService;
    @Autowired
    private RestTemplateUtil restTemplateUtil;


    /**
     * 列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<DeliveryPersonnel>
     * @author keNan
     * @since 2025-03-12
     */
    @Override
    public List<DeliveryPersonnel> getList(DeliveryPersonnelSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        List<DeliveryPersonnel> list = deliveryPersonnelDao.selectListBySearch(request);
        return list;
    }


    /**
     * 校验手机号格式以及是否被注册
     *
     * @param deliveryPersonnelRequest
     */
    @Override
    public void check(DeliveryPersonnelRequest deliveryPersonnelRequest) {
        String deliveryPersonnelPhone = deliveryPersonnelRequest.getDeliveryPersonnelPhone();
        boolean checkPhone = PhoneUtil.checkPhone(deliveryPersonnelPhone);
        if (!checkPhone) {
            throw new CrmebException("手机号格式不对");
        }
        //校验手机号是否被注册
        LambdaQueryWrapper<DeliveryPersonnel> lq = new LambdaQueryWrapper<>();
        lq.eq(DeliveryPersonnel::getDeliveryPersonnelPhone, deliveryPersonnelPhone);
        DeliveryPersonnel deliveryPersonnel = getOne(lq);
        if (deliveryPersonnel != null && !deliveryPersonnelPhone.equals(deliveryPersonnel.getDeliveryPersonnelPhone())) {
            throw new CrmebException("手机号已被其他配送员注册");
        }
        LambdaQueryWrapper<SaleRoom> lqsr = new LambdaQueryWrapper<>();
        lqsr.eq(SaleRoom::getRoomPhone, deliveryPersonnelPhone);
        List<SaleRoom> listsr = saleRoomDao.selectList(lqsr);
        if (CollectionUtil.isNotEmpty(listsr)) {
            throw new CrmebException("手机号已被其他门店注册");
        }
    }


    /**
     * 配送员登录
     *
     * @param request
     * @return
     */
    @Override
    public DeliveryPersonnelLoginResponse login(DeliveryPersonnelLoginRequest request) {
        DeliveryPersonnelLoginResponse loginResponse = new DeliveryPersonnelLoginResponse();
        Integer uid = null;
        String phone = null;
        String name = null;
        LambdaQueryWrapper<DeliveryPersonnel> lq = new LambdaQueryWrapper<>();
        lq.eq(DeliveryPersonnel::getDeliveryPersonnelPhone, request.getDeliveryPersonnelPhone());
        lq.eq(DeliveryPersonnel::getPassword, request.getPassword());
        DeliveryPersonnel deliveryPersonnel = getOne(lq);
        if (null == deliveryPersonnel) {
            //查询门店账号
            LambdaQueryWrapper<SaleRoom> lqsr = new LambdaQueryWrapper<>();
            lqsr.eq(SaleRoom::getRoomPhone, request.getDeliveryPersonnelPhone());
            lqsr.eq(SaleRoom::getRoomPassword, request.getPassword());
            SaleRoom saleRoom = saleRoomDao.selectOne(lqsr);
            if (null == saleRoom) {
                throw new CrmebException("账号密码不对");
            }
            loginResponse.setLoginType(2);
            uid = saleRoom.getId().intValue();
            phone = saleRoom.getRoomPhone();
            name = saleRoom.getRoomName();
        } else {
            loginResponse.setLoginType(1);
            uid = deliveryPersonnel.getId();
            phone = deliveryPersonnel.getDeliveryPersonnelPhone();
            name = deliveryPersonnel.getDeliveryPersonnelName();
            if (0 == deliveryPersonnel.getIsDisable()) {
                throw new CrmebException("该账号已被禁用");
            }
        }

        //生成token
        loginResponse.setToken(tokenComponent.createDeliveryPersonnelUserToken(uid, 60 * 24 * 7l));
        loginResponse.setId(uid);
        loginResponse.setDeliveryPersonnelName(name);
        loginResponse.setDeliveryPersonnelPhone(CrmebUtil.maskMobile(phone));

        //手机号中间四位base64加密返回前端
        String phoneNew = phone.substring(3, 7);
        String phoneEncode = Base64.encodeBase64String(phoneNew.getBytes());
        loginResponse.setExtend(phoneEncode);

        return loginResponse;
    }


    /**
     * 查询配送员正在配送的订单列表
     *
     * @param deliveryPersonnelOrderStatusRequest
     * @return
     */
    @Override
    public PageInfo<OrderFrontDataResponse> orderManage(DeliveryPersonnelOrderStatusRequest deliveryPersonnelOrderStatusRequest) {
        DeliveryPersonnel deliveryPersonnelInfo = userService.getDeliveryPersonnelInfo();
        Page<Object> page = PageHelper.startPage(deliveryPersonnelOrderStatusRequest.getPage(), deliveryPersonnelOrderStatusRequest.getLimit());
        List<Order> orderList = deliveryPersonnelDao.selectOrderList(deliveryPersonnelInfo.getId(), deliveryPersonnelOrderStatusRequest.getOrderStatus(), 11, 12, 6, 0, 9);

        List<OrderFrontDataResponse> responseList = CollUtil.newArrayList();
        for (Order order : orderList) {
            OrderFrontDataResponse infoResponse = new OrderFrontDataResponse();
            BeanUtils.copyProperties(order, infoResponse);
            // 订单详情对象列表
            List<OrderDetail> orderDetailList = orderDetailService.getByOrderNo(order.getOrderNo());
            List<OrderInfoFrontDataResponse> infoResponseList = CollUtil.newArrayList();
            orderDetailList.forEach(e -> {
                OrderInfoFrontDataResponse orderInfoResponse = new OrderInfoFrontDataResponse();
                BeanUtils.copyProperties(e, orderInfoResponse);
                infoResponseList.add(orderInfoResponse);
            });
            infoResponse.setOrderInfoList(infoResponseList);

            //如果是门店自提和同城配送的话，需要给门店的联系电话
            if (null != order.getRoomId() && (order.getShippingType().equals(OrderConstants.ORDER_SHIPPING_TYPE_PICK_UP) || order.getShippingType().equals(OrderConstants.ORDER_SHIPPING_TYPE_SAME_CITY))) {
                SaleRoom saleRoom = saleRoomDao.selectById(order.getRoomId());
                infoResponse.setRoomPhone(saleRoom != null ? saleRoom.getRoomPhone() : "");
            }

            responseList.add(infoResponse);
        }
        return CommonPage.copyPageInfo(page, responseList);

    }


    /**
     * 配送员扫门店订单二维码
     *
     * @param orderNo
     * @return
     */
    @Override
    public Boolean scanCode(String orderNo) {
        if (!(orderNo.startsWith(OrderConstants.ORDER_PREFIX_PLATFORM) || orderNo.startsWith(OrderConstants.ORDER_PREFIX_MERCHANT) || orderNo.startsWith(OrderConstants.ORDER_PREFIX_REFUND))) {
            throw new CrmebException("无效的二维码");
        }
        if (orderNo.startsWith(OrderConstants.ORDER_PREFIX_PLATFORM)) {
            DeliveryPersonnel deliveryPersonnelInfo = userService.getDeliveryPersonnelInfo();
            Order order = orderService.getByOrderNo(orderNo);
            if (null == order) {
                throw new CrmebException("无效的二维码");
            }
            if (null != order.getDeliveryPersonnelId()) {
                throw new CrmebException("过期的二维码");
            }
//        if (null != order.getReservationDeliveryStartTime() && null != order.getReservationDeliveryEndTime()) {
//            if (!CrmebDateUtil.isInTimeRange(order.getReservationDeliveryStartTime(), order.getReservationDeliveryEndTime())) {
//                throw new CrmebException("未到预约配送时间,暂不能配送");
//            }
//        }
            LambdaUpdateWrapper<Order> luw = new LambdaUpdateWrapper<>();
            luw.set(Order::getDeliveryPersonnelId, deliveryPersonnelInfo.getId());
            luw.set(Order::getStatus, OrderConstants.ORDER_STATUS_DELIVERY_IN_PROGRESS);
            luw.set(Order::getUpdateTime, new Date());
            luw.eq(Order::getOrderNo, orderNo);
            return orderService.update(luw);
        } else if (orderNo.startsWith(OrderConstants.ORDER_PREFIX_REFUND)) {
            RefundOrder refundOrder = refundOrderService.getOneByRefundOrderNo(orderNo);
            DeliveryPersonnel deliveryPersonnelInfo = userService.getDeliveryPersonnelInfo();
            refundOrder.setDeliveryPersonnelId(deliveryPersonnelInfo != null ? deliveryPersonnelInfo.getId() : null)
                    .setRefundStatus(OrderConstants.MERCHANT_REFUND_ORDER_STATUS_DOOR_ING);
            return refundOrderService.updateById(refundOrder);
        }
        return false;
    }


    /**
     * 配送员已送达
     * 订单状态（0：待支付，1：待发货,2：部分发货， 3：待核销，4：待收货,5：已收货,6：已完成，9：已取消10：待配送（同城配送的状态） 11：配送中（同城配送的状态） 12：已送达（同城配送的状态））")
     *
     * @param orderNo
     * @return
     */
    @Override
    public Boolean delivered(String orderNo) {
        LambdaUpdateWrapper<Order> luw = new LambdaUpdateWrapper<>();
        luw.set(Order::getStatus, OrderConstants.ORDER_STATUS_DELIVERY_COMPLETED);
        luw.set(Order::getUpdateTime, new Date());
        luw.eq(Order::getOrderNo, orderNo);
        return orderService.update(luw);
    }


    /**
     * 调整订单
     *
     * @param productAttrAdjustRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = CrmebException.class)
    public Boolean adjustOrder(ProductAttrAdjustRequest productAttrAdjustRequest) {
        if (CollectionUtil.isEmpty(productAttrAdjustRequest.getRemoveList()) && CollectionUtil.isEmpty(productAttrAdjustRequest.getAddList())) {
            throw new CronException("未调整商品");
        }
//        if (CollectionUtils.isEqualCollection(productAttrAdjustRequest.getRemoveList(), productAttrAdjustRequest.getAddList())) {
//            throw new CronException("删除和新增的商品不能完全一样");
//        }
        List<ProductAttrAndNumberRequest> list = productAttrAdjustRequest.getRemoveList().stream()
                .filter(p1 -> productAttrAdjustRequest.getAddList().stream().anyMatch(p2 -> p2.getShopSpecId().equals(p1.getShopSpecId()) && p2.getNumber().equals(p1.getNumber()))) // 过滤出在两个列表中都存在的对象
                .collect(Collectors.toList()); // 收集到List中

//        if (CollectionUtil.isNotEmpty(list)) {
////            throw new CronException("删除和新增的商品不能有一样的");
////        }

        //为货到付款订单
        Order order = orderService.getByOrderNo(productAttrAdjustRequest.getOrderNo());
        Integer totalNum = order.getTotalNum();
        if (order == null) {
            throw new CronException("订单不存在");
        }
        //如果是payType支付方式是offline(同城配送的线下付款)
//        if ("offline".equals(order.getPayType())) {
//
//        }
        BigDecimal addSumPrice = BigDecimal.ZERO;
        BigDecimal removeSumPrice = BigDecimal.ZERO;
        //移除的商品规格不为空
        if (CollectionUtil.isNotEmpty(productAttrAdjustRequest.getRemoveList())) {
            List<ProductAttrAndNumberRequest> removeList = productAttrAdjustRequest.getRemoveList();
            List specIdList = removeList.stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());
            removeSumPrice = productAttrValueDao.selectSumPriceByIdList(specIdList);
            //更新订单详情表
            removeOrderDetail(productAttrAdjustRequest);
            totalNum = totalNum - productAttrAdjustRequest.getRemoveList().stream().mapToInt(ProductAttrAndNumberRequest::getNumber).sum();
        }

        //添加的商品不为空
        if (CollectionUtil.isNotEmpty(productAttrAdjustRequest.getAddList())) {
            //需要补的差价
            List<ProductAttrAndNumberRequest> addList = productAttrAdjustRequest.getAddList();
            List specIdList = addList.stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());
            //查询每个商品规格的单价
            Map<Integer, ProductAttrValue> map = productAttrValueDao.selectPriceByIdList(specIdList);
            for (ProductAttrAndNumberRequest productAttrAndNumberRequest : addList) {
                BigDecimal price = map.get(productAttrAndNumberRequest.getShopSpecId()).getPrice();
                addSumPrice = addSumPrice.add(price.multiply(BigDecimal.valueOf(productAttrAndNumberRequest.getNumber())));
            }
            //新增订单详情表
            //查询添加的规格信息
            addOrderDetail(productAttrAdjustRequest, order.getDeliveryPersonnelId());
            totalNum = totalNum + productAttrAdjustRequest.getAddList().stream().mapToInt(ProductAttrAndNumberRequest::getNumber).sum();
        }

        if (addSumPrice.compareTo(removeSumPrice) > 0) {
            //addSumPrice 大于 removeSumPrice时,该订单调整为需补差价订单
            //更新原订单为调整订单以及需要补的差价,设置为待支付订单,使用户去支付差价
            LambdaUpdateWrapper<Order> luw = new LambdaUpdateWrapper();
            luw.set(Order::getIsAdjustOrder, 1);
            luw.set(Order::getDifferencePrice, addSumPrice.subtract(removeSumPrice));
            luw.set(Order::getStatus, OrderConstants.ORDER_STATUS_WAIT_PAY);
            luw.set(Order::getPaid, false);
            luw.set(Order::getTotalNum, totalNum);
            luw.set(Order::getNewOutTradeNo, CrmebUtil.getOrderNo(OrderConstants.ORDER_PREFIX_ADJUST));
            luw.eq(Order::getOrderNo, productAttrAdjustRequest.getOrderNo());
            orderService.update(luw);
        } else if (addSumPrice.compareTo(removeSumPrice) == 0) {
            //addSumPrice 等于 removeSumPrice时,该订单调整为已完成订单
            //removeOrderDetail(productAttrAdjustRequest);
            //addOrderDetail(productAttrAdjustRequest, order.getDeliveryPersonnelId());

//            LambdaUpdateWrapper<Order> luw = new LambdaUpdateWrapper();
//            luw.set(Order::getIsAdjustOrder, 1);
//            luw.eq(Order::getOrderNo, productAttrAdjustRequest.getOrderNo());
//            orderService.update(luw);
        } else {
            //addSumPrice 小于 removeSumPrice时,该订单调整为待退款订单
            //更新原订单为调整订单以及需要退的差价,设置为待退款订单
            LambdaUpdateWrapper<Order> luw = new LambdaUpdateWrapper();
            luw.set(Order::getIsAdjustOrder, 1);
            luw.set(Order::getRefundPrice, removeSumPrice.subtract(addSumPrice));
            luw.set(Order::getTotalNum, totalNum);
            luw.set(Order::getStatus, OrderConstants.ORDER_STATUS_REFUND);
            luw.eq(Order::getOrderNo, productAttrAdjustRequest.getOrderNo());
            orderService.update(luw);
        }
        return true;
    }

    @Override
    public Boolean sendLocation(LocationRequest locationRequest) {
        DeliveryPersonnel deliveryPersonnelInfo = userService.getDeliveryPersonnelInfo();
        Boolean aLong = redisUtil.set(RedisConstants.LOCATION + deliveryPersonnelInfo.getId(), locationRequest.getLocation());
        return aLong;
    }


    /**
     * 查询配送员是否有待配送订单
     *
     * @param status
     * @return
     */
    @Override
    public Boolean toDelivered(Integer status) {
        DeliveryPersonnel deliveryPersonnelInfo = userService.getDeliveryPersonnelInfo();
        List<Order> orderList = deliveryPersonnelDao.selectOrderList(deliveryPersonnelInfo.getId(), status);
        Boolean flag = false;
        if (CollectionUtil.isNotEmpty(orderList)) {
            flag = true;
        }
        return flag;
    }


    /**
     * 根据账户获取车辆列表
     *
     * @param userId
     * @return
     */
    @Override
    public Map vehicleList(String userId) {
//        Map<String, String> headerMap = new HashMap<String, String>();
//        Map<String, String> paramMap = new HashMap<String, String>();
//        paramMap.put("userId", userId);
//        makeParam(userId, headerMap, paramMap);
//
//        //获取accessToken
//        String accessToken = "";
//        String s = TuHuUtil.sendPost(headerMap, paramMap, TuHuUtil.getAccessTokenUrl);
//        JSONObject jsonObject = (JSONObject) JSONObject.parse(s);
//        Integer code = (Integer) jsonObject.get("code");
//        if (0 == code) {
//            JSONObject j = (JSONObject) jsonObject.get("result");
//            accessToken = (String) j.get("accessToken");
////            return accessToken;
//        } else {
//            log.info("获取accessToken失败...错误码是{}", code);
//        }
        return new HashMap();
    }


    /**
     * 根据IMEI获取最新定位数据
     *
     * @param imei
     * @return
     */
    @Override
    public String getLocationByImei(String imei) {
        AtomicReference<String> location = new AtomicReference<>("");
        String accessToken = (String) redisUtil.hget(RedisConstants.TU_HU_PARAM, RedisConstants.TU_HU_ACCESS_TOKEN);
        if (StrUtil.isBlank(accessToken)) {
            accessToken = TuHuUtil.getAccessToken();
            redisUtil.hset(RedisConstants.TU_HU_PARAM, RedisConstants.TU_HU_ACCESS_TOKEN, accessToken, TuHuUtil.expireTime);
        }
        List<TuHuLocationDto> list = TuHuUtil.getLocationByImei(imei, accessToken);
//        JSONObject jsonObject = (JSONObject) JSONObject.parse(s);
//        Integer code = (Integer) jsonObject.get("code");
        list.forEach(tuHuLocationDto -> {
            if (imei.equals(tuHuLocationDto.getImei())) {
                location.set(StrUtil.format("{},{}", tuHuLocationDto.getLat(), tuHuLocationDto.getLng()));
            }
        });
//        if (0 == code) {
//            List<TuHuLocationDto> j = (List<TuHuLocationDto>) jsonObject.get("result");
//        } else {
//            log.info("获取最新定位数据失败...错误码code={}", code);
//        }
        return location.get();
//        Map<String, String> headerMap = new HashMap<String, String>();
//        headerMap.put("X-Access-Token", "xxxxxxxxxxxxxx");
//        Map<String, String> paramMap = new HashMap<String, String>();
//        paramMap.put("imeis", imei);
//        TuHuUtil.sendPost(headerMap, paramMap, TuHuUtil.getLocationUrl);
    }


    /**
     * 我的个人中心配送地图定位数据
     *
     * @return
     */
    @Override
    public Map<String, String> getCenter() {
        Map resultMap = MapUtil.newHashMap();
        Integer userId = userService.getUserId();
        List<OrderLocationDto> l = orderService.getListByUserIdStatus(userId, 4, 11);
        if (CollUtil.isEmpty(l)) {
            resultMap.put("isEmpty", false);
            return resultMap;
        }
        AtomicReference<String> location = new AtomicReference<>("");
        OrderLocationDto orderLocationDto = l.get(0);

        if (StrUtil.isBlank(orderLocationDto.getGpsNumber())) {
            throw new CrmebException("该配送专员未绑定车辆,请先绑定车辆");
        }
        String accessToken = (String) redisUtil.hget(RedisConstants.TU_HU_PARAM, RedisConstants.TU_HU_ACCESS_TOKEN);
        if (StrUtil.isBlank(accessToken)) {
            accessToken = TuHuUtil.getAccessToken();
            redisUtil.hset(RedisConstants.TU_HU_PARAM, RedisConstants.TU_HU_ACCESS_TOKEN, accessToken, TuHuUtil.expireTime);
        }
        List<TuHuLocationDto> locationByImei = TuHuUtil.getLocationByImei(orderLocationDto.getGpsNumber(), accessToken);
        locationByImei.forEach(tuHuLocationDto -> {
            if (orderLocationDto.getGpsNumber().equals(tuHuLocationDto.getImei())) {
                location.set(StrUtil.format("{},{}", tuHuLocationDto.getLat(), tuHuLocationDto.getLng()));
            }
        });
        //计算距离
        try {
            String distance = PositionUtil.calculateDistance(StrUtil.format("{},{}", orderLocationDto.getConsigneeLatitude(), orderLocationDto.getConsigneeLongitude()), location.get());
            resultMap.put("distance", distance);
        } catch (Exception e) {

        }
        resultMap.put("location", location.get());
        resultMap.put("orderNo", orderLocationDto.getOrderNo());
        resultMap.put("minute", 30);
        resultMap.put("isEmpty", true);
        return resultMap;
    }

//    private void makeParam(String userId, Map<String, String> headerMap, Map<String, String> paramMap) {
//        headerMap.put("Content-Type", "application/x-www-form-urlencoded");
//        // 先调用获取token接口获取token，获取到的token配置在请求头中，再去请求其它接口
//        // headerMap.put("X-Access-Token", "xxxxxxxxxxxxxx");
//        // 公共参数
//        paramMap.put("appKey", TuHuUtil.app_key);
//        paramMap.put("v", "1.0");
//        paramMap.put("timestamp", DateUtil.timeOfLongToStr(System.currentTimeMillis()));
//        paramMap.put("signMethod", "md5");
//        paramMap.put("format", "json");
//
//        //私有参数_获取token
//        //userId为分配密钥对应的账户的手机号码
//
//        paramMap.put("expiresIn", "7200");
//
//        //私有参数_根据账户，获取该账户下的所有IMEI信息
//        //paramMap.put("userId", "您的用户名");
//
//        // 计算签名
//        String sign = "";
//        try {
//            sign = SignUtils.signTopRequest(paramMap, TuHuUtil.app_secret, "md5");
//            paramMap.put("sign", sign);
//            System.out.println(sign);
//        } catch (IOException e) {
//            System.err.println(e);
//        }
//
//    }


    private void removeOrderDetail(ProductAttrAdjustRequest productAttrAdjustRequest) {
        List<ProductAttrAndNumberRequest> removeList = productAttrAdjustRequest.getRemoveList();
        List specIdList = removeList.stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());
        removeList.forEach(productAttrAndNumberRequest -> {
            orderDetailDao.updateSubtractPayNum(productAttrAdjustRequest.getOrderNo(), productAttrAndNumberRequest.getShopSpecId(), productAttrAndNumberRequest.getNumber());
        });
        //把购买数量为0的商品订单设置为逻辑已删除
        LambdaUpdateWrapper<OrderDetail> l = new LambdaUpdateWrapper();
        l.set(OrderDetail::getIsDel, 1);
        l.eq(OrderDetail::getOrderNo, productAttrAdjustRequest.getOrderNo());
        l.eq(OrderDetail::getPayNum, 0);
        l.in(OrderDetail::getAttrValueId, specIdList);
        orderDetailService.update(l);
    }

    private void addOrderDetail(ProductAttrAdjustRequest productAttrAdjustRequest, Integer deliveryPersonnelId) {
        List<ProductAttrAndNumberRequest> addList = productAttrAdjustRequest.getAddList();
        List specIdList = addList.stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());
        Map<Integer, ProductAttrValue> pMap = productAttrValueDao.selectListByIdList(specIdList);
        List<OrderDetail> add = CollectionUtil.newArrayList();
        //查询原订单
        Order byOrderNo = orderService.getByOrderNo(productAttrAdjustRequest.getOrderNo());

        specIdList.forEach(id -> {
            ProductAttrValue productAttrValue = pMap.get(id);
            OrderDetail o = new OrderDetail()
                    .setAttrValueId((Integer) id)
                    .setDeliveryPersonnelId(deliveryPersonnelId)
                    .setProductName(productAttrValue.getProductName())
                    .setPayNum(addList.stream().filter(f -> f.getShopSpecId().equals(id)).findFirst().get().getNumber());
            BeanUtil.copyProperties(productAttrValue, o);
            BeanUtil.copyProperties(byOrderNo, o);
            o.setMerId(productAttrValue.getMerId())
                    .setPayPrice(productAttrValue.getPrice().multiply(BigDecimal.valueOf(addList.stream().filter(f -> f.getShopSpecId().equals(id)).findFirst().get().getNumber())));
            add.add(o);
        });
        orderDetailService.saveBatch(add);
    }


    private void addOrderDetailV2(ProductAttrAdjustRequest productAttrAdjustRequest, Integer deliveryPersonnelId) {
        List<ProductAttrAndNumberRequest> addList = productAttrAdjustRequest.getAddList();
        List specIdList = addList.stream().map(m -> m.getShopSpecId()).collect(Collectors.toList());
        Map<Integer, ProductAttrValue> pMap = productAttrValueDao.selectListByIdList(specIdList);
        List<OrderDetail> add = CollectionUtil.newArrayList();
        //查询原订单
        Order byOrderNo = orderService.getByOrderNo(productAttrAdjustRequest.getOrderNo());
        //查询原详情订单
        List<OrderDetail> orderDetailList = orderDetailService.getByOrderNo(productAttrAdjustRequest.getOrderNo());

        //交集
        Set<Integer> s = addList.stream()
                .map(ProductAttrAndNumberRequest::getShopSpecId)
                .filter(id -> orderDetailList.stream().anyMatch(p -> p.getAttrValueId().equals(id)))
                .collect(Collectors.toSet());

        //在原来的订单详情规格上加数量
        if (CollectionUtil.isNotEmpty(s)) {
            s.forEach(p -> {
                orderDetailDao.updateAddPayNum(productAttrAdjustRequest.getOrderNo(), p, addList.stream().filter(f -> f.getShopSpecId() == p).findFirst().get().getNumber());
            });
        }

        specIdList.forEach(id -> {
            //只新增原来不存在的订单详情规格
            if (!s.contains(id)) {
                ProductAttrValue productAttrValue = pMap.get(id);
                OrderDetail o = new OrderDetail()
                        .setAttrValueId((Integer) id)
                        .setDeliveryPersonnelId(deliveryPersonnelId)
                        .setProductName(productAttrValue.getProductName())
                        .setPayNum(addList.stream().filter(f -> f.getShopSpecId().equals(id)).findFirst().get().getNumber());
                BeanUtil.copyProperties(productAttrValue, o);
                BeanUtil.copyProperties(byOrderNo, o);
                o.setMerId(productAttrValue.getMerId())
                        .setPayPrice(productAttrValue.getPrice().multiply(BigDecimal.valueOf(addList.stream().filter(f -> f.getShopSpecId().equals(id)).findFirst().get().getNumber())));
                add.add(o);
            }
        });
        orderDetailService.saveBatch(add);
    }


}

